package com.hc.componentspringboot.service.impl;

import com.hc.componentspringboot.bean.Authority;
import com.hc.componentspringboot.bean.Customer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户登录校验服务类
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    CustomerServiceImpl customerService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Customer customer = customerService.getCustomer(username);
        List<Authority> authorityList = customerService.getCustomerAuthority(username);
        List<SimpleGrantedAuthority> grantedAuthorityList = authorityList.stream()
                .map(authority ->
                    new SimpleGrantedAuthority(authority.getAuthority())
                ).collect(Collectors.toList());
        if(customer != null){
            UserDetails userDetails = new User(customer.getUsername(),customer.getPassword(),grantedAuthorityList);
            return userDetails;
        }else {
            throw new UsernameNotFoundException("用户不存在");
        }
    }
}
